/**
 * ChatInput - 消息输入组件
 * 提供用户输入界面，支持多行输入和发送消息
 */
import React, { useState, useRef } from 'react';
import TextareaAutosize from 'react-textarea-autosize';
import { Send, Loader2 } from 'lucide-react';
import { motion } from "motion/react";

interface ChatInputProps {
    onSendMessage: (message: string) => Promise<void>;
    isLoading: boolean;
}

const ChatInput: React.FC<ChatInputProps> = ({ onSendMessage, isLoading }) => {
    const [message, setMessage] = useState('');
    const textareaRef = useRef<HTMLTextAreaElement>(null);

    const handleSendMessage = async () => {
        if (message.trim() && !isLoading) {
            await onSendMessage(message);
            setMessage('');
            textareaRef.current?.focus();
        }
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    };

    return (
        <div className="relative">
            <div className="relative rounded-2xl bg-white shadow-md border border-gray-200 overflow-hidden">
                <TextareaAutosize
                    ref={textareaRef}
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="输入消息。按 Enter 发送消息，Shift + Enter 换行"
                    maxRows={5}
                    disabled={isLoading}
                    className="w-full px-4 py-3 pr-12 resize-none focus:outline-none bg-transparent"
                />

                <motion.button
                    whileTap={{ scale: 0.9 }}
                    whileHover={{ scale: 1.05 }}
                    onClick={handleSendMessage}
                    disabled={!message.trim() || isLoading}
                    className={`
            absolute right-3 bottom-3
            w-8 h-8 rounded-full flex items-center justify-center
            ${message.trim() && !isLoading
                            ? 'bg-blue-600 hover:bg-blue-700 text-white'
                            : 'bg-gray-200 text-gray-400 cursor-not-allowed'}
            transition-colors
          `}
                    aria-label="发送消息"
                >
                    {isLoading ? (
                        <Loader2 size={18} className="animate-spin" />
                    ) : (
                        <Send size={18} />
                    )}
                </motion.button>
            </div>
        </div>
    );
};

export default ChatInput;
